﻿Imports System.Data
Imports System.Data.SqlClient
Imports System.Drawing
Imports System.IO

Partial Class Imagenes_PerImagen
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Page.IsPostBack Then Return
        Dim cPerCodigo As String
        Dim Ancho As Integer = 0
        Dim Altura As Integer = 0
        If Request("cPerCodigo") = "" Then
            cPerCodigo = IdentityUser.UserCode
        Else
            cPerCodigo = Request("cPerCodigo")
        End If
        If Not String.IsNullOrEmpty(Request("Height")) Then
            Integer.TryParse(Request("Height"), Altura)
        End If
        If Not String.IsNullOrEmpty(Request("Width")) Then
            Integer.TryParse(Request("Width"), Ancho)
        End If
        If Altura > 0 And Ancho > 0 Then
            RenderResizedImage(cPerCodigo, Ancho, Altura)
        Else
            ShowImage(cPerCodigo, Ancho, Altura)
        End If
    End Sub

    Private Sub ShowImage(ByVal cPerCodigo As String, ByVal Ancho As Integer, ByVal Alto As Integer)
        Try
            Dim Connection As New SqlConnection(ConfigurationManager.ConnectionStrings("sqlCnAsync").ConnectionString)
            Dim Cmd As New SqlCommand("sp_PerImg_Get", Connection)
            Cmd.CommandType = CommandType.StoredProcedure
            Cmd.Parameters.Add("@cPerCodigo", SqlDbType.Char, 10).Value = cPerCodigo
            Connection.Open()
            Dim Result As IAsyncResult = Cmd.BeginExecuteReader(CommandBehavior.SequentialAccess + CommandBehavior.SingleRow + CommandBehavior.CloseConnection)
            Using reader As SqlDataReader = Cmd.EndExecuteReader(Result)
                RenderImage(reader, Ancho, Alto)
            End Using
        Catch ex As Exception
            RenderError(" [Error] ")
        End Try
    End Sub

    Private Sub RenderResizedImage(ByVal cPerCodigo As String, ByVal Ancho As Integer, ByVal Alto As Integer)
        Try
            Dim Connection As New SqlConnection(ConfigurationManager.ConnectionStrings("sqlCnAsync").ConnectionString)
            Dim Cmd As New SqlCommand("sp_PerImg_Get", Connection)
            Cmd.CommandType = CommandType.StoredProcedure
            Cmd.Parameters.Add("@cPerCodigo", SqlDbType.Char, 10).Value = cPerCodigo
            Connection.Open()
            Dim Result As IAsyncResult = Cmd.BeginExecuteReader(CommandBehavior.SequentialAccess + CommandBehavior.SingleRow + CommandBehavior.CloseConnection)
            Using reader As SqlDataReader = Cmd.EndExecuteReader(Result)
                Try

                    reader.Read()
                    If Not reader.HasRows Then
                        RenderError(" [No Foto] ", Ancho, Alto)
                        Exit Sub
                    End If

                    Dim byteArray As Byte() = DirectCast(reader("iPerImaFoto"), Byte())

                    'Dim imageToBeResized As System.Drawing.Image = System.Drawing.Image.FromStream(New System.IO.MemoryStream(byteArray))
                    'Dim imageToBeShowed As Bitmap = New Bitmap(imageToBeResized, ancho, alto)

                    Dim dbImage As System.Drawing.Image = System.Drawing.Image.FromStream(New System.IO.MemoryStream(byteArray))
                    Dim imageToBeShowed As System.Drawing.Image = dbImage.GetThumbnailImage(Ancho, Alto, Nothing, New System.IntPtr())

                    Context.Response.Clear()
                    Context.Response.ContentType = "image/jpeg"
                    imageToBeShowed.Save(Context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)

                Catch ex As Exception
                    RenderError(" [Error] ", Ancho, Alto)
                End Try


            End Using
        Catch ex As Exception
            RenderError(" [Error] ", Ancho, Alto)
        End Try
    End Sub

    Private Sub RenderImage(ByVal Reader As SqlDataReader, ByVal Ancho As Integer, ByVal Alto As Integer)

        Reader.Read()
        If Not Reader.HasRows Then
            RenderError("[No Foto]", Ancho, Alto)
            Exit Sub
        End If

        Const bufferSize As Integer = 1024
        Dim startIndex As Long = 0
        Dim outbyte(bufferSize - 1) As Byte
        Dim retval As Long

        Context.Response.Clear()
        Context.Response.ContentType = "image/jpeg"

        Do
            retval = Reader.GetBytes(1, startIndex, outbyte, 0, bufferSize)
            ' reposition the start index
            startIndex += bufferSize
            ' output buffer
            Response.BinaryWrite(outbyte)
            Response.Flush()
        Loop While (retval = bufferSize)
    End Sub

    Private Sub RenderError(ByVal Msg As String, Optional ByVal Width As Integer = 150, Optional ByVal Height As Integer = 200)
        Context.Response.Clear()
        Context.Response.ContentType = "image/jpeg"
        ' calculate the image width by message length
        If Width = 0 Then Width = 150
        If Height = 0 Then Height = 200
        Dim bitmap As Bitmap = New Bitmap(Width, Height)
        Dim g As Graphics = Graphics.FromImage(bitmap)
        ' create a background filler
        g.FillRectangle(New SolidBrush(Color.Gray), 0, 0, bitmap.Width, bitmap.Height)
        ' draw our message
        g.DrawString(Msg, New Font("Tahoma", 8, FontStyle.Bold), New SolidBrush(Color.White), New PointF(5, 5))
        ' stream it to the output
        bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
    End Sub

End Class
